package com.example.wemedia.controller.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.apis.article.iArticleClient;
import com.example.apis.behaviour.IBehaviourClient;
import com.example.model.acl.pojos.Acl_user;
import com.example.model.article.pojos.ApArticle;
import com.example.model.common.dtos.PageRequestDto;
import com.example.model.common.dtos.ResponseResult;
import com.example.model.user.pojos.ApUser;
import com.example.model.wemedia.dtos.WmNewsDto;
import com.example.model.wemedia.dtos.WmNewsPageReqDto;
import com.example.user.mapper.AclUserMapper;
import com.example.utils.common.AppJwtUtil;
import com.example.wemedia.mapper.WmMessageMapper;
import com.example.wemedia.service.WmMaterialService;
import com.example.wemedia.service.WmNewsService;
import com.example.wemedia.service.WmUserService;
import com.tencentcloudapi.es.v20180416.models.EsConfigSetInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@RestController
@RequestMapping("/backend/v1/wemedia")
public class WeMediaController {

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private WmMaterialService wmMaterialService;

    @Autowired
    private WmNewsService wmNewsService;

//    @PostMapping("/in")
//    public ResponseResult login(@RequestBody WmLoginDto dto){
//        return wmUserService.login(dto);
//    }

    @PostMapping("/down_or_up")
    public ResponseResult downOrUp(@RequestBody WmNewsDto wmNewsDto){
        return wmNewsService.downOrUp(wmNewsDto);
    }

    @GetMapping("/allMediaUser")
    @PreAuthorize("hasAuthority('admin')")
    public ResponseResult getAllMediaUser(){
        return ResponseResult.okResult(wmUserService.list());
    }

    @PostMapping("/uploadPicture")
    public ResponseResult uploadPicture(@RequestParam(value = "file") MultipartFile multipartFile, HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();
        log.info("上传图片的用户id为: {}",userId);
        return wmMaterialService.uploadPicture(multipartFile,userId);
    }

    /*
    素材列表
     */
    @PostMapping("/list")
    public ResponseResult findList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();
        return wmMaterialService.findList(pageRequestDto,userId);
    }

    /**
     * 删除素材
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/deleteOne/{id}")
    public ResponseResult deleteOne(@PathVariable String id,HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();

        return wmMaterialService.deleteOne(id,userId);
    }

    @GetMapping("/deleteOneMyArticle/{id}")
    public ResponseResult deleteOneMyArticle(@PathVariable String id,HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();
        return wmNewsService.deleteOneMyArticle(id,userId);
    }


    @PostMapping("/getApArticleList/{keyword}")
    public ResponseResult getApArticleList(HttpServletRequest request,@PathVariable("keyword") String keyword){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();

        if(keyword.equals("all")){
            return ResponseResult.okResult(wmMessageMapper.getApArticleList(Integer.valueOf(userId),null));
        }
        return ResponseResult.okResult(wmMessageMapper.getApArticleList(Integer.valueOf(userId),keyword));
    }

    @PostMapping("/getApArticleListAll/{keyword}")
    public ResponseResult getApArticleListAll(HttpServletRequest request,@PathVariable("keyword") String keyword){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();

        if(keyword.equals("all")){
            return ResponseResult.okResult(wmMessageMapper.getApArticleListAll(null));
        }
        return ResponseResult.okResult(wmMessageMapper.getApArticleListAll(keyword));
    }

    @PostMapping("/getApArticleContent/{id}")
    public ResponseResult getApArticleContent(@PathVariable("id") String id){
        return ResponseResult.okResult(wmMessageMapper.getApArticleContent(id));
    }

    /**
     * 我的新闻列表
     * @param dto
     * @param request
     * @return
     */
    @PostMapping("/findNewsList")
    public ResponseResult findNewsList(@RequestBody WmNewsPageReqDto dto,HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();

        return wmNewsService.findNewsList(dto,userId);
    }
    @PostMapping("/submit")
    public ResponseResult submitNews(@RequestBody WmNewsDto wmNewsDto,HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();
        return wmNewsService.submit(wmNewsDto,userId);
    }

    @GetMapping("/channels")
    public ResponseResult getChannels(){
        return wmNewsService.getChannels();
    }

    @Autowired
    private WmMessageMapper wmMessageMapper;

    @GetMapping("/messages")
    public ResponseResult getMessages(HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.orderByDesc("time");
        return ResponseResult.okResult(wmMessageMapper.selectList(queryWrapper));
    }

    @Autowired
    private IBehaviourClient iBehaviourClient;

    @PostMapping("/fansList")
    public ResponseResult getFansList(HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());
        System.out.println("userId "+userId);

        return iBehaviourClient.getFansList(userId);
    }

    @Autowired
    private AclUserMapper aclUserMapper;

    @PostMapping("/getAclUserData")
    public ResponseResult getAclUserData(){
        List<Acl_user> acl_users = aclUserMapper.selectList(null);
        for (int i = 0;i < acl_users.size();i++){
            if("1".equals(acl_users.get(i).getId())){
                acl_users.remove(i);
            }
        }
        return ResponseResult.okResult(acl_users);
    }

    @PostMapping("/forbidAclUser/{id}")
    public ResponseResult forbidAclUser(@PathVariable("id") Integer id){
        Acl_user acl_user = aclUserMapper.selectById(id);
        acl_user.setForbid(1);
        aclUserMapper.updateById(acl_user);
        return ResponseResult.okResult("操作成功");
    }

    @PostMapping("/allowAclUser/{id}")
    public ResponseResult allowAclUser(@PathVariable("id") Integer id){
        Acl_user acl_user = aclUserMapper.selectById(id);
        acl_user.setForbid(0);
        aclUserMapper.updateById(acl_user);
        return ResponseResult.okResult("操作成功");
    }

    @PostMapping("/getAllArticle")
    public ResponseResult getAllArticle(){
        return ResponseResult.okResult(wmMessageMapper.getAllArticle());
    }

    @Autowired
    private iArticleClient iArticleClient;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @PostMapping("/delOneArticle/{id}")
    public ResponseResult delOneArticle(@PathVariable("id") String id) throws IOException {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("115.159.84.44", 9200, "http")));

        DeleteByQueryRequest request = new DeleteByQueryRequest("app_info_article");
        request.setQuery(QueryBuilders.termQuery("id", id));

//        DeleteRequest deleteRequest = new DeleteRequest("id",id);
//        restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
        BulkByScrollResponse response = client.deleteByQuery(request, RequestOptions.DEFAULT);

        ResponseResult articleByAclId = iArticleClient.getArticleByArticleId(id);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(articleByAclId.getData()));
        ApArticle apArticle = jsonObject.toJavaObject(ApArticle.class);
        Integer userId = Math.toIntExact(apArticle.getAuthorId());
        Acl_user acl_user = aclUserMapper.selectById(userId);
        acl_user.setArticleNum(acl_user.getArticleNum()-1);
        aclUserMapper.updateById(acl_user);

        wmMessageMapper.delApArticleByArticleId(id);
        return ResponseResult.okResult("操作成功");
    }

    @PostMapping("/getManAndWomanNum")
    public ResponseResult getManAndWomanNum(HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        AtomicReference<Integer> count_man = new AtomicReference<>(0);
        AtomicReference<Integer> count_woman = new AtomicReference<>(0);
        List<ApUser> fansList = wmMessageMapper.getFansList(userId);
        fansList.forEach(item -> {
            if(item.getSex()){
                count_man.updateAndGet(v -> v + 1);
            }else{
                count_woman.updateAndGet(v -> v + 1);
            }
        });
        Map<String, AtomicReference<Integer>> map = new HashMap<>();
        map.put("male",count_man);
        map.put("female",count_woman);
        return ResponseResult.okResult(map);
    }

    @PostMapping("/getFansNumIn7Days")
    public ResponseResult getFansNumIn7Days(HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        List<Map<String,String>> fansNumList = new ArrayList<>();
        List<String> dateList = getSevenDate();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateList.forEach(date-> {
            Map<String, String> map = new HashMap<>();

            Date new_date_1 = null;
            Integer fansNums = null;
            try {
                Date new_date = dateFormat.parse(date);
                new_date_1 = DateUtils.addDays(new_date, 1);
                fansNums = wmMessageMapper.getFansNumIn7Days(dateFormat.format(new_date_1), userId);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            map.put("date",date);
            map.put("value", String.valueOf(fansNums));
            fansNumList.add(map);
        });

        return ResponseResult.okResult(fansNumList);
    }

    @PostMapping("/getThumbsNumIn7Days")
    public ResponseResult getThumbNumsIn7Days(HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        List<Map<String,String>> fansNumList = new ArrayList<>();
        List<String> dateList = getSevenDate();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateList.forEach(date-> {
            Map<String, String> map = new HashMap<>();

            Date new_date_1 = null;
            Integer fansNums = null;
            try {
                Date new_date = dateFormat.parse(date);
                new_date_1 = DateUtils.addDays(new_date, 1);
                fansNums = wmMessageMapper.getArticleThumbIn7Days(dateFormat.format(new_date_1), userId);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            map.put("date",date);
            map.put("value", String.valueOf(fansNums));
            fansNumList.add(map);
        });

        return ResponseResult.okResult(fansNumList);
    }

    @PostMapping("/getCollectionsNumIn7Days")
    public ResponseResult getCollectionNumsIn7Days(HttpServletRequest request){
        String token = request.getHeader("token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        List<Map<String,String>> fansNumList = new ArrayList<>();
        List<String> dateList = getSevenDate();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateList.forEach(date-> {
            Map<String, String> map = new HashMap<>();

            Date new_date_1 = null;
            Integer fansNums = null;
            try {
                Date new_date = dateFormat.parse(date);
                new_date_1 = DateUtils.addDays(new_date, 1);
                fansNums = wmMessageMapper.getCollectionNubIn7Days(dateFormat.format(new_date_1), userId);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            map.put("date",date);
            map.put("value", String.valueOf(fansNums));
            fansNumList.add(map);
        });

        return ResponseResult.okResult(fansNumList);
    }



    public List<String> getSevenDate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            Date date = DateUtils.addDays(new Date(), -i);
            String formatDate = dateFormat.format(date);
            dateList.add(formatDate);
        }
        Collections.reverse(dateList);
        return dateList;
    }
}
